'use strict';

const Service = require('../core/common');

class GoodsService extends Service {
  findAll(params = {}) {
    const { ctx } = this;

    const { title, userId, status } = ctx.request.query;

    const where = {};

    // 我的全部抽奖
    if (userId) {
      // TODO
      const about = {
        include: [{
          where,
          model: ctx.model.GoodsPrizes,
        }, {
          attributes: [],
          where: { id: userId },
          model: ctx.model.Users,
          through: {
            where: {
              status,
              userId,
            }
          }
        }],
        distinct: true,
        ...this.paging(),
      };

      return ctx.model.Goods.findAndCountAll(about);
    }

    // 需要查关联字段
    title && Object.assign(where, {
      title: {
        ['$like']: `%${title}%`
      }
    });

    // TODO
    const about = {
      include: [{
        where,
        model: ctx.model.GoodsPrizes,
      }, {
        model: ctx.model.GoodsFigures,
      }],
      distinct: true,
      ...this.paging(params),
    };

    return ctx.model.Goods.findAndCountAll(about);
  }

  findById(id = 0) {
    const { ctx } = this;

    return ctx.model.Goods.findOne({
      include: [{
        model: ctx.model.GoodsPrizes,
      }, {
        model: ctx.model.GoodsFigures,
      }, {
        model: ctx.model.Banners,
      }],
      where: { id }
    });
  }

  create(params = {}) {
    const { ctx } = this;

    return ctx.model.Goods.create(params, {
      include: [{
        model: ctx.model.GoodsPrizes,
      }, {
        model: ctx.model.GoodsFigures,
      }],
    });
  }

  update(params = {}, where = {}) {
    const { ctx } = this;

    return ctx.model.Goods.update(params, where);
  }

  destroy(params) {
    const { ctx } = this;

    return ctx.model.Goods.destroy(params);
  }
}

module.exports = GoodsService;